/**

*/
import React, { PureComponent } from 'react';
import { PrimaryC, ModalC, PrimaryGhostC, AvailableAssetC, TradeHoldC, TableC } from '../../../../comps';
import { message } from 'antd';
import style from './index.less';
import EftBuySellC from './eftBuySell';
import BaseInfoC from './baseInfo';
import EtfStockC from './etfStock';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import { uniqueKey } from '../../../../utils/commonFunc';

class AddEtfOrder extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      tradingcode: undefined, //证券代码
      exchangecode: undefined, //交易市场
      portfolio: undefined, //组合id
      secuabbr: undefined, //证券名称
      currentAsset: {}, //当前资金
      holdAmount: {}, //持仓数量
      querys: {}, //二次确认的数据
      isShow: false, //是否显示二次确认弹窗
      trailColumns: [], //试算结果列表
      trailDataSource: [], //试算结果数据
      trailModel: false, //试算模态框
      productCode: undefined, //产品code
      portfolioCode: undefined, //组合code
      uid: '',
    };
  }

  componentDidMount() {
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  //指令下达 簿记保存 获取form表单数据并校验
  confirmClick = () => {
    const {
      user: { currentUser = {} },
      type,
      dispatch,
    } = this.props;
    const { currentAsset, holdAmount, uid } = this.state;
    if (!this.etfBuySell.state.isCanOrder && type == 1) {
      //在点击“下达”时，若标记指示未配置指令，则提示用户“该组合为配置指令，无法下发指令。
      message.warning(this.props.errorSetMsg);
      return;
    }
    this.etfBuySell.formGroupThis.props.form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        if (fieldsValue.amount && fieldsValue.amount > 1000000) {
          message.warning('数量不能大于一百万');
          return;
        }
        if (fieldsValue.zlprice && fieldsValue.zlprice == 0) {
          message.warning('金额不能为0');
          return;
        }
        if (fieldsValue.direction == '1') {
          //买入
          if (currentAsset.t1 !== undefined) {
            if (currentAsset.t1 < fieldsValue.zlprice) {
              message.error('T+1可用资金不足!');
              return;
            }
          } else {
            message.error('T+1可用资金不足!');
            return;
          }
        }
        if (fieldsValue.direction == '2') {
          //卖出
          if (holdAmount.available !== undefined) {
            if (holdAmount.available < fieldsValue.amount) {
              message.error('可用数量不足!');
              return;
            }
          } else {
            message.error('可用数量不足!');
            return;
          }
        }
        if (fieldsValue.type == '1' && fieldsValue.direction == '1') {
          //交易类型为市价且方向为买入
          if (currentAsset.t1 !== undefined) {
            if (currentAsset.t1 < fieldsValue.zlprice) {
              message.error('T+1可用资金不足!');
              return;
            }
          } else {
            message.error('T+1可用资金不足!');
            return;
          }
        }
        if (this.props.type == 2) {
          //新增簿记
          fieldsValue.method = '0';
        }
        fieldsValue.userid = currentUser.userId;
        fieldsValue.username = currentUser.name;
        fieldsValue.secuabbr = this.state.secuabbr;
        fieldsValue.parValueTotal = fieldsValue.zlprice;
        fieldsValue.tradingcode = fieldsValue.zqdm.split('-')[1];
        fieldsValue.uid = uid;
        fieldsValue.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
        delete fieldsValue.zlprice;
        delete fieldsValue.zqdm;

        if (this.props.type == 1) {
          //二次确认弹窗
          if (this.state.isShow) {
            this.orderSave(fieldsValue);
          } else {
            this.setState({
              isShow: true,
              querys: fieldsValue,
            });
          }
        } else {
          this.orderSave(fieldsValue);
        }
      }
    });
  };

  //指令下达 簿记保存请求后台
  orderSave = (params) => {
    const {
      user: { currentUser = {} },
      dispatch,
    } = this.props;
    let url = this.props.type == 1 ? 'etfOrderM/orderSave' : this.props.type == 11 ? 'portfolioTrialAddM/etfSave' : 'etfOrderM/tradeBookSave';

    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (data) => {
        if (data) {
          if (this.props.type == 2 || this.props.type == 11) {
            //簿记下达成功
            this.props.onOk();
            this.cancelClick(); //初始化form表单
          } else {
            //指令下达成功
            this.cancelClick(); //初始化form表单
            this.handleCancel(); //关闭弹窗
          }
        }
        const uid = uniqueKey();
        uid.then((r) => {
          this.setState({ uid: r });
        });
      },
    });
  };
  //点击取消 重置
  cancelClick = () => {
    // const { type } = this.props;
    if (this.props.type == 2 || this.props.type == 11) {
      //簿记点击取消 抛出oncancel事件
      this.props.onCancel();
    }
    //指令下达  重置表单
    this.etfBuySell.formGroupThis.props.form.resetFields();
    this.etfBuySell.setState({
      typeStuas: false,
      isCanOrder: true,
    });
    this.tradingcodeOnChange({});
    this.portfolioOnChange(undefined);
  };
  //组合id变更
  portfolioOnChange = (e) => {
    this.setState({
      portfolio: e,
    });
  };
  //证券code变更 传入证券code和交易市场
  tradingcodeOnChange = (values) => {
    this.setState({
      tradingcode: values.tradingcode,
      exchangecode: values.exchangecode,
      secuabbr: values.secuabbr,
    });
  };
  //二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };
  // 二次确认modal框
  showModal = () => {
    const { querys, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 1034,
      height: 200,
      className: 'confirmOrder',
      confirmLoading: loading.effects['etfOrderM/orderSave'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.confirmClick} onCancel={this.handleCancel}>
        <EftBuySellC type={'4'} info={querys} />
      </ModalC>
    );
  };

  //试算按钮点击
  trialOnClick = () => {
    const {
      user: { currentUser = {} },
      type,
      dispatch,
    } = this.props;
    const { currentAsset, holdAmount, productCode, portfolioCode } = this.state;

    this.etfBuySell.formGroupThis.props.form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        if (fieldsValue.amount && fieldsValue.amount > 1000000) {
          message.warning('数量不能大于一百万');
          return;
        }
        if (fieldsValue.zlprice && fieldsValue.zlprice == 0) {
          message.warning('金额不能为0');
          return;
        }
        if (fieldsValue.direction == '1') {
          //买入
          if (currentAsset.t1 !== undefined) {
            if (currentAsset.t1 < fieldsValue.zlprice) {
              message.error('T+1可用资金不足!');
              return;
            }
          } else {
            message.error('T+1可用资金不足!');
            return;
          }
        }
        if (fieldsValue.direction == '2') {
          //卖出
          if (holdAmount.available !== undefined) {
            if (holdAmount.available < fieldsValue.amount) {
              message.error('可用数量不足!');
              return;
            }
          } else {
            message.error('可用数量不足!');
            return;
          }
        }
        if (fieldsValue.type == '1' && fieldsValue.direction == '1') {
          //交易类型为市价且方向为买入
          if (currentAsset.t1 !== undefined) {
            if (currentAsset.t1 < fieldsValue.zlprice) {
              message.error('T+1可用资金不足!');
              return;
            }
          } else {
            message.error('T+1可用资金不足!');
            return;
          }
        }
        if (this.props.type == 2) {
          //新增簿记
          fieldsValue.method = '0';
        }
        fieldsValue.userid = currentUser.userId;
        fieldsValue.username = currentUser.name;
        fieldsValue.secuabbr = this.state.secuabbr;
        fieldsValue.parValueTotal = fieldsValue.zlprice;
        (fieldsValue.tradingcode = fieldsValue.zqdm.split('-')[1]), delete fieldsValue.zlprice;
        delete fieldsValue.zqdm;
        let querys = {
          productCode: productCode, //产品code
          portfolioCode: portfolioCode, //组合code
          tenant: currentUser.tenant, //租户code
          businessType: '9',
          type: '9',
          trade9: fieldsValue,
        };
        this.setState({ trailModel: true }, () => {
          dispatch({
            type: 'trailM/trialData',
            payload: querys,
            callback: (res) => {
              if (res) {
                this.setState({
                  trailColumns: res.columns,
                  trailDataSource: res.dataSource,
                });
              } else {
                this.setState({
                  trailColumns: [],
                  trailDataSource: [],
                });
              }
            },
          });
        });
      }
    });
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };
  render() {
    const { loading, type } = this.props;
    const { tradingcode, exchangecode, portfolio } = this.state;
    let url = this.props.type == 1 ? 'etfOrderM/orderSave' : this.props.type == 11 ? 'portfolioTrialAddM/etfSave' : 'etfOrderM/tradeBookSave';
    return (
      <div className={style.etfOrder}>
        <div>
          <div>
            <div style={{ marginBottom: '20px' }}>
              <BaseInfoC tradingcode={tradingcode} exchangecode={exchangecode} type={type} />
            </div>
            <div>
              <EtfStockC tradingcode={tradingcode} exchangecode={exchangecode} height={'286px'} type={type} />
            </div>
          </div>
          <div>
            <div style={{ marginBottom: '20px' }}>
              <AvailableAssetC
                portfolio={portfolio}
                onChange={(e) => {
                  this.setState({
                    currentAsset: e,
                  });
                }}
              />
            </div>
            <div style={{ marginBottom: '20px' }}>
              <TradeHoldC
                securityType={'9'} //ETF
                portfolio={portfolio}
                tradingcode={tradingcode}
                exchangecode={exchangecode}
                onChange={(e) => {
                  this.setState(
                    {
                      holdAmount: e,
                    },
                    () => {
                      this.etfBuySell.changeinvestmentType();
                    },
                  );
                }}
              />
            </div>
            <EftBuySellC
              type={this.props.type}
              onRef={(ref) => (this.etfBuySell = ref)}
              productOnChange={() => {}}
              portfolioOnChange={this.portfolioOnChange}
              tradingcodeOnChange={this.tradingcodeOnChange}
              portfolioCode={this.portfolioCode}
              productCode={this.productCode}
              position={this.state.holdAmount}
            />
            <div className={'btnOperate grayBg'}>
              {/* {this.props.type == "2" && <PrimaryC
                loading={loading.effects['trailM/trialData'] === true}
                onClick={() => this.trialOnClick()}
                title={'试算'}
                style={{ marginRight: "10px" }}
              />} */}
              <PrimaryC loading={loading.effects[url] === true} title={this.props.type == 1 ? '下达' : '确定'} onClick={this.confirmClick} />
              <PrimaryGhostC title={'取消'} onClick={this.cancelClick} style={{ marginLeft: '10px' }} />
            </div>
            {this.state.trailModel && this.showTrail()}
          </div>
        </div>
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
      </div>
    );
  }
}
export default connect(({ etfOrderM, userM: user, portfolioTrialAddM, loading, TrailM, isAccountConfiguredM }) => ({
  etfOrderM,
  user,
  portfolioTrialAddM,
  loading,
  TrailM,
  errorSetMsg: isAccountConfiguredM.msg,
}))(AddEtfOrder);
